package com.heo.server;

import org.apache.log4j.Logger;

import com.heo.pub.ServerConfig;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * 接收外部向设备发送指令入口
 */

public class ControllerServer implements Runnable
{
  static final int PORT = ServerConfig.CONTROL_PORT;
  private static Logger log = Logger.getLogger(ControllerServer.class);

  public ControllerServer()
  {

  }

  @Override
  public void run()
  {
    try
    {
      bind();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public void bind() throws Exception
  {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try
    {
      ServerBootstrap b = new ServerBootstrap();
      b.option(ChannelOption.SO_BACKLOG, 1024);
      b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>()// 构建Handler处理流程
      {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception
        {
          ChannelPipeline p = socketChannel.pipeline();
          // p.addLast(new HttpServerCodec());
          // p.addLast(new HttpServerHandler());
          int MAX_CONTENT_LENGTH = 1024 * 100;
          p.addLast(new HttpServerCodec(), new HttpObjectAggregator(MAX_CONTENT_LENGTH), new ControllerServerHandler());
        }
      });

      Channel ch = b.bind(PORT).sync().channel();

      log.info("[server][controller]接收控制指令端口启动成功。监听端口[" + PORT + "]，允许访问的源IP[" + ServerConfig.getControlIp() + "]");

      ch.closeFuture().sync();
    }
    finally
    {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
}
